<template>
	<view class="order-detail-container">
		<!-- 导航栏 -->
		<uni-nav-bar title="订单详情" left-icon="back" @clickLeft="goBack" />
		
		<!-- 加载中 -->
		<view v-if="loading" class="loading-container">
			<uni-load-more status="loading" />
		</view>
		
		<!-- 订单数据为空 -->
		<view v-else-if="!order" class="empty-container">
			<uni-icons type="info" size="48" color="#ccc"></uni-icons>
			<text class="empty-text">订单不存在或已被删除</text>
			<button class="back-btn" @click="goBack">返回</button>
		</view>
		
		<!-- 订单信息 -->
		<view v-else class="order-content">
			<!-- 订单状态 -->
			<view class="status-section">
				<view class="status-header">
					<uni-icons :type="getStatusIcon(order.status)" size="24" :color="getStatusColor(order.status)"></uni-icons>
					<text class="status-text" :style="{ color: getStatusColor(order.status) }">{{ getStatusText(order.status) }}</text>
				</view>
				<text class="order-number">订单号：{{ order.orderNumber }}</text>
				<text class="create-time">下单时间：{{ formatTime(order.createdAt) }}</text>
			</view>
			
			<!-- 商品信息 -->
			<view class="product-section">
				<view class="section-title">商品信息</view>
				<view class="product-item">
					<image :src="order.productImage || '/static/default-product.png'" class="product-image" mode="aspectFill"></image>
					<view class="product-info">
						<text class="product-title">{{ order.productTitle }}</text>
						<view class="price-info">
							<text class="final-price">¥{{ order.finalPrice }}</text>
							<text class="quantity">x{{ order.quantity }}</text>
						</view>
						<text class="delivery-method">{{ getDeliveryMethodText(order.deliveryMethod) }}</text>
					</view>
				</view>
			</view>
			
			<!-- 交易信息 -->
			<view class="trade-section">
				<view class="section-title">交易信息</view>
				<view class="info-row">
					<text class="info-label">买家</text>
					<text class="info-value">{{ order.buyerName }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">卖家</text>
					<text class="info-value">{{ order.sellerName }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">交易方式</text>
					<text class="info-value">{{ getDeliveryMethodText(order.deliveryMethod) }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">支付状态</text>
					<text class="info-value" :style="{ color: getPaymentStatusColor(order.paymentStatus) }">{{ order.paymentStatusName }}</text>
				</view>
			</view>
			
			<!-- 收货地址 -->
			<view v-if="order.deliveryMethod === 2 && order.buyerAddress" class="address-section">
				<view class="section-title">收货地址</view>
				<view class="address-info">
					<view class="receiver-info">
						<text class="receiver-name">{{ order.buyerAddress.receiverName }}</text>
						<text class="receiver-phone">{{ order.buyerAddress.receiverPhone }}</text>
					</view>
					<text class="address-detail">{{ order.buyerAddress.province }}{{ order.buyerAddress.city }}{{ order.buyerAddress.district }}{{ order.buyerAddress.detailAddress }}</text>
				</view>
			</view>
			
			<!-- 物流信息 -->
			<view v-if="order.deliveryMethod === 2 && order.trackingNumber" class="logistics-section">
				<view class="section-title">
					<text>物流信息</text>
					<text class="tracking-number">{{ order.trackingNumber }}</text>
				</view>
				<view class="logistics-status" @click="viewTrackingDetail">
					<text class="logistics-text">{{ order.deliveryStatusName }}</text>
					<uni-icons type="right" size="16" color="#999"></uni-icons>
				</view>
			</view>
			
			<!-- 留言信息 -->
			<view v-if="order.buyerMessage || order.sellerMessage" class="message-section">
				<view class="section-title">留言信息</view>
				<view v-if="order.buyerMessage" class="message-item">
					<text class="message-label">买家留言：</text>
					<text class="message-content">{{ order.buyerMessage }}</text>
				</view>
				<view v-if="order.sellerMessage" class="message-item">
					<text class="message-label">卖家备注：</text>
					<text class="message-content">{{ order.sellerMessage }}</text>
				</view>
			</view>
			
			<!-- 金额信息 -->
			<view class="amount-section">
				<view class="section-title">金额信息</view>
				<view class="amount-row">
					<text class="amount-label">商品金额</text>
					<text class="amount-value">¥{{ order.finalPrice }}</text>
				</view>
				<view class="amount-row">
					<text class="amount-label">数量</text>
					<text class="amount-value">{{ order.quantity }}</text>
				</view>
				<view class="amount-row total">
					<text class="amount-label">总计</text>
					<text class="amount-value total-price">¥{{ order.totalAmount }}</text>
				</view>
			</view>
			
			<!-- 操作按钮 -->
			<view class="action-section">
				<view class="action-buttons">
					<!-- 取消订单 -->
					<button v-if="canCancel" class="action-btn cancel-btn" @click="cancelOrderDirect">取消订单</button>
					
					<!-- 卖家确认订单 -->
					<button v-if="canSellerConfirm" class="action-btn confirm-btn" @click="sellerConfirmOrder">确认订单</button>
					
					<!-- 买家确认收货 -->
					<button v-if="canBuyerConfirm" class="action-btn confirm-btn" @click="confirmReceipt">确认收货</button>
				</view>
			</view>
		</view>
		
		<!-- 取消订单弹窗
		<uni-popup ref="cancelPopup" type="dialog">
			<uni-popup-dialog 
				title="取消订单" 
				content="请选择取消原因"
				:before-close="true"
				@close="closeCancelDialog"
				@confirm="confirmCancel">
				<view class="cancel-reasons">
					<radio-group @change="onCancelReasonChange">
						<label v-for="reason in cancelReasons" :key="reason.value" class="reason-item">
							<radio :value="reason.value" :checked="cancelReason === reason.value" />
							<text class="reason-text">{{ reason.label }}</text>
						</label>
					</radio-group>
				</view>
			</uni-popup-dialog>
		</uni-popup> -->
	</view>
</template>

<script>
import { getOrderDetail, cancelOrder, sellerConfirmOrder, confirmReceipt } from '@/api/order.js'
import { ORDER_STATUS, ORDER_STATUS_TEXT, DELIVERY_METHOD_TEXT, PAYMENT_STATUS } from '@/api/order.js'
import { getUserInfo } from '@/utils/auth.js'

export default {
	data() {
		return {
			orderId: '',
			order: null,
			loading: true
		}
	},
	computed: {
		// 是否可以取消
		canCancel() {
			return this.order && this.order.status === ORDER_STATUS.PENDING_SELLER_CONFIRM
		},
		// 卖家是否可以确认订单
		canSellerConfirm() {
			return this.order && this.order.status === ORDER_STATUS.PENDING_SELLER_CONFIRM && this.isSeller
		},
		// 买家是否可以确认收货
		canBuyerConfirm() {
			return this.order && this.order.status === ORDER_STATUS.PENDING_DELIVERY && this.isBuyer
		},
		// 是否为卖家
		isSeller() {
			const currentUser = getUserInfo()
			return this.order && currentUser && this.order.sellerId === currentUser.id
		},
		// 是否为买家
		isBuyer() {
			const currentUser = getUserInfo()
			return this.order && currentUser && this.order.buyerId === currentUser.id
		}
	},
	onLoad(options) {
		if (options.id) {
			this.orderId = options.id
			this.loadOrderDetail()
		}
	},
	methods: {
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
		// 加载订单详情
		async loadOrderDetail() {
			try {
				this.loading = true
				console.log('订单ID:', this.orderId)
				const res = await getOrderDetail(this.orderId)
				console.log('API响应:', res)
				
				if (res && res.success && res.data) {
					this.order = res.data
					console.log('订单数据已设置:', this.order)
				} else if (res && res.code === 200 && res.data) {
					// 兼容不同的响应格式
					this.order = res.data
					console.log('订单数据已设置(code=200):', this.order)
				} else {
					console.log('API响应异常:', res)
					uni.showToast({ title: res?.message || '获取订单详情失败', icon: 'none' })
				}
			} catch (error) {
				console.error('加载订单详情失败:', error)
				uni.showToast({ title: '获取订单详情失败', icon: 'none' })
			} finally {
				this.loading = false
				console.log('加载完成，loading:', this.loading, 'order:', this.order)
			}
		},
		
		// 获取状态图标
		getStatusIcon(status) {
			const iconMap = {
				[ORDER_STATUS.PENDING_SELLER_CONFIRM]: 'gear',
				[ORDER_STATUS.PENDING_DELIVERY]: 'location',
				[ORDER_STATUS.COMPLETED]: 'star',
				[ORDER_STATUS.CANCELLED]: 'close'
			}
			return iconMap[status] || 'info'
		},
		
		// 获取状态颜色
		getStatusColor(status) {
			const colorMap = {
				[ORDER_STATUS.PENDING_SELLER_CONFIRM]: '#ff9500',
				[ORDER_STATUS.PENDING_DELIVERY]: '#007aff',
				[ORDER_STATUS.COMPLETED]: '#34c759',
				[ORDER_STATUS.CANCELLED]: '#ff3b30'
			}
			return colorMap[status] || '#666'
		},
		
		// 获取状态文本
		getStatusText(status) {
			// 对于待卖家确认状态，根据用户角色显示不同文本
			if (status === ORDER_STATUS.PENDING_SELLER_CONFIRM) {
				if (this.isSeller) {
					return '待确认'
				} else if (this.isBuyer) {
					return '待卖家确认'
				}
			}
			// 对于待收货状态，根据用户角色显示不同文本
			if (status === ORDER_STATUS.PENDING_DELIVERY) {
				if (this.isBuyer) {
					return '待买家确认'
				} else if (this.isSeller) {
					return '待收货'
				}
			}
			return ORDER_STATUS_TEXT[status] || '未知状态'
		},
		
		// 获取交易方式文本
		getDeliveryMethodText(method) {
			return DELIVERY_METHOD_TEXT[method] || '未知方式'
		},
		
		// 获取支付状态颜色
		getPaymentStatusColor(status) {
			const colorMap = {
				[PAYMENT_STATUS.UNPAID]: '#ff9500',
				[PAYMENT_STATUS.PAYING]: '#007aff',
				[PAYMENT_STATUS.PAID]: '#34c759',
				[PAYMENT_STATUS.FAILED]: '#ff3b30',
				[PAYMENT_STATUS.REFUNDED]: '#666'
			}
			return colorMap[status] || '#666'
		},
		
		// 格式化时间
		formatTime(time) {
			if (!time) return ''
			const date = new Date(time)
			return date.toLocaleString('zh-CN')
		},
		
		// 直接取消订单
		async cancelOrderDirect() {
			uni.showModal({
				title: '取消订单',
				content: '确定要取消这个订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await cancelOrder(this.orderId, {
								reason: '不需要了'
							})
							
							if (result.success || result.code === 200) {
								uni.showToast({ title: '订单已取消', icon: 'success' })
								this.loadOrderDetail() // 重新加载订单详情
							} else {
								uni.showToast({ title: result.message || '取消订单失败', icon: 'none' })
							}
						} catch (error) {
							console.error('取消订单失败:', error)
							uni.showToast({ title: '取消订单失败', icon: 'none' })
						}
					}
				}
			})
		},
		
		// 卖家确认订单
		async sellerConfirmOrder() {
			try {
				const res = await sellerConfirmOrder(this.orderId, {
					sellerMessage: '确认接单'
				})
				
				if (res.success || res.code === 200) {
					uni.showToast({ title: '订单确认成功', icon: 'success' })
					this.loadOrderDetail() // 重新加载订单详情
				} else {
					uni.showToast({ title: res.message || '确认失败', icon: 'none' })
				}
			} catch (error) {
				console.error('卖家确认订单失败:', error)
				uni.showToast({ title: '确认失败', icon: 'none' })
			}
		},
		
		// 确认收货
		async confirmReceipt() {
			uni.showModal({
				title: '确认收货',
				content: '确认已收到商品吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await confirmReceipt(this.orderId)
							
							if (result.success) {
								uni.showToast({ title: '确认收货成功', icon: 'success' })
								this.loadOrderDetail() // 重新加载订单详情
							} else {
								uni.showToast({ title: result.message || '确认收货失败', icon: 'none' })
							}
						} catch (error) {
							console.error('确认收货失败:', error)
							uni.showToast({ title: '确认收货失败', icon: 'none' })
						}
					}
				}
			})
		},
		
		// 查看物流详情
		viewTrackingDetail() {
			if (!this.order.trackingNumber) {
				uni.showToast({ title: '暂无物流信息', icon: 'none' })
				return
			}
			
			uni.navigateTo({
				url: `/pages/order/tracking?id=${this.orderId}&trackingNumber=${this.order.trackingNumber}`
			})
		}
	}
}
</script>

<style scoped>
.order-detail-container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 100px;
}

.loading-container {
	padding: 50px 0;
	text-align: center;
}

.empty-container {
	padding: 100px 20px;
	text-align: center;
	background: white;
	margin: 10px;
	border-radius: 8px;
}

.empty-text {
	font-size: 16px;
	color: #666;
	display: block;
	margin: 20px 0;
}

.back-btn {
	padding: 8px 24px;
	background: #007aff;
	color: white;
	border: none;
	border-radius: 20px;
	font-size: 14px;
}

/* 通用区块样式 */
.status-section,
.product-section,
.trade-section,
.address-section,
.logistics-section,
.message-section,
.amount-section {
	background: white;
	margin-bottom: 10px;
	padding: 15px;
}

.section-title {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	margin-bottom: 15px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}

/* 订单状态 */
.status-header {
	display: flex;
	align-items: center;
	margin-bottom: 12px;
}

.status-text {
	font-size: 18px;
	font-weight: 600;
	margin-left: 8px;
}

.order-number,
.create-time {
	font-size: 14px;
	color: #666;
	display: block;
	margin-bottom: 4px;
}

/* 商品信息 */
.product-item {
	display: flex;
	align-items: flex-start;
}

.product-image {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	margin-right: 12px;
	flex-shrink: 0;
}

.product-info {
	flex: 1;
}

.product-title {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	display: block;
	margin-bottom: 8px;
	line-height: 1.4;
}

.price-info {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.final-price {
	font-size: 18px;
	font-weight: 600;
	color: #ff4757;
	margin-right: 8px;
}

.quantity {
	font-size: 14px;
	color: #666;
}

.delivery-method {
	font-size: 14px;
	color: #007aff;
	background: #f0f8ff;
	padding: 2px 8px;
	border-radius: 4px;
}

/* 交易信息 */
.info-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 0;
	border-bottom: 1px solid #f0f0f0;
}

.info-row:last-child {
	border-bottom: none;
}

.info-label {
	font-size: 14px;
	color: #666;
}

.info-value {
	font-size: 14px;
	color: #333;
}

/* 收货地址 */
.address-info {
	padding: 12px 0;
}

.receiver-info {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.receiver-name {
	font-size: 16px;
	font-weight: 500;
	color: #333;
	margin-right: 12px;
}

.receiver-phone {
	font-size: 14px;
	color: #666;
}

.address-detail {
	font-size: 14px;
	color: #666;
	line-height: 1.4;
}

/* 物流信息 */
.tracking-number {
	font-size: 12px;
	color: #999;
}

.logistics-status {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 0;
}

.logistics-text {
	font-size: 14px;
	color: #333;
}

/* 留言信息 */
.message-item {
	margin-bottom: 12px;
}

.message-item:last-child {
	margin-bottom: 0;
}

.message-label {
	font-size: 14px;
	color: #666;
	display: block;
	margin-bottom: 4px;
}

.message-content {
	font-size: 14px;
	color: #333;
	line-height: 1.4;
}

/* 金额信息 */
.amount-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8px 0;
}

.amount-row.total {
	border-top: 1px solid #e0e0e0;
	margin-top: 8px;
	padding-top: 12px;
}

.amount-label {
	font-size: 14px;
	color: #666;
}

.amount-value {
	font-size: 14px;
	color: #333;
}

.total-price {
	font-size: 18px;
	font-weight: 600;
	color: #ff4757;
}

/* 操作按钮 */
.action-section {
	padding: 20px 15px;
	background: white;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	z-index: 100;
	border-top: 1px solid #e0e0e0;
}

.action-buttons {
	display: flex;
	gap: 12px;
}

.action-btn {
	flex: 1;
	height: 44px;
	border: none;
	border-radius: 22px;
	font-size: 14px;
	font-weight: 500;
}

.cancel-btn {
	background: #f5f5f5;
	color: #666;
}

.pay-btn {
	background: #ff4757;
	color: white;
}

.confirm-btn {
	background: #34c759;
	color: white;
}

.track-btn {
	background: #007aff;
	color: white;
}
</style>